﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using MillerApp.Business.Stock;
using MillerApp.Stock.Common;
using MillerApp.DataContract.Common;

namespace MillerApp.Stock.Others
{
    public partial class AcquireMoneyFlow : MillerApp.UserControls.SubFormBase
    {
        public AcquireMoneyFlow()
        {
            InitializeComponent();
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            lblMsg.Text = "";
            Thread oThread = null;
            btnGet.Enabled = false;
            try
            {
                if (oThread != null)
                {
                    oThread.Abort();
                }
                SecurityService service = new SecurityService();
                service.StartDate = datePK1.Value.Date;
                service.EndDate = datePK2.Value.Date;
                ParameterizedThreadStart threadStart = new ParameterizedThreadStart(service.AutoGetInOrOutflows);
                oThread = new Thread(threadStart);
                DelegateMessageHanldler method = new DelegateMessageHanldler(HanlderMsgMethod);
                oThread.Start(method);
            }
            catch (Exception ex)
            {
                
            }
            finally
            {
                Thread.Sleep(200);
                btnGet.Enabled = true;
            }
        }

        private object HanlderMsgMethod(Dictionary<string, object> args)
        {
            try
            {
                //增加这个就不会出现以下的异常了
                if (!this.IsHandleCreated)
                {
                    return null;
                }
                foreach (var item in args)
                {
                    DelegateMessageHanldler method = new DelegateMessageHanldler(HanlderMsgMethod2);
                    //窗口关闭的时候会提示以下异常：
                    //在创建窗口句柄之前，不能在控件上调用 Invoke 或 BeginInvoke
                    lblMsg.Invoke(method, args);
                }
            }
            catch { }
            return null;
        }

        private object HanlderMsgMethod2(Dictionary<string, object> args)
        {
            foreach (var item in args)
            {
                lblMsg.Text = item.Value.ToString();
                if (item.Key.Trim().ToLower() == "FINISHED".ToLower())
                {
                    MessageBox.Show(item.Value.ToString());
                }
            }
            return null;
        }
    }
}
